﻿using System;
using System.IO;
using System.Security.Permissions;
using System.Threading;

namespace MightyPoke.GUI
{
    public class Poke
    {
        private const int MAX_PATH = 32767;
        private static FileIOPermission permission;
        private readonly string drive;
        private readonly string file;
        private readonly int hours;
        private readonly int minutes;
        private readonly int seconds;

        private volatile bool _shouldStop;

        public Poke(string drive, string file, int hours, int minutes, int seconds)
        {
            this.drive = drive;
            this.seconds = seconds;
            this.minutes = minutes;
            this.hours = hours;
            this.file = file;
        }

        public void PokeIt()
        {
            while (!_shouldStop)
            {
                WriteToFile(file, drive);
                Thread.Sleep(new TimeSpan(0, hours, minutes, seconds));
            }
        }

        public void Stop()
        {
            _shouldStop = true;
        }

        private static void WriteToFile(string file, string drive)
        {
            string path = (string.Format(drive + @":\" + file +StringResources.File_Extension));
            if (path.Length > MAX_PATH)
                return;
            permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, path);
            var writer = new StreamWriter(path);

            writer.Write(TimeStamp());
            writer.Close();
         
        }

        public static string TimeStamp()
        {
            return DateTime.Now.ToString();
        }
    }
}